// 2D射击游戏主逻辑（改进版）
const GAME = {
    // 游戏基本属性
    canvas: null,
    ctx: null,
    width: 800,
    height: 600,
    player: null,
    enemies: [],
    bullets: [],
    explosions: [],
    particles: [],
    powerUps: [],
    score: 0,
    health: 100,
    enemiesKilled: 0,
    isGameActive: false,
    isPaused: false,
    keys: {},
    mouse: { x: 0, y: 0 },
    enemySpawnTimer: 0,
    bossSpawnTimer: 0,
    enemySpawnRate: 1000, // 普通敌人每秒生成一个（毫秒）
    bossSpawnRate: 5000, // Boss每5秒生成一个（毫秒）
    lastTime: 0,
    level: 1,
    backgroundOffsetX: 0,
    backgroundOffsetY: 0,
    
    // 场景配置
    scenes: [
        { name: '太空', bgColor: '#0a0a1a', stars: 150, gradient: '#000033' },
        { name: '森林', bgColor: '#003300', trees: 50, gradient: '#005500' },
        { name: '城市', bgColor: '#222222', buildings: 30, gradient: '#333333' },
        { name: '火山', bgColor: '#552222', lava: true, gradient: '#773333' }
    ],
    currentScene: 0,
    
    // 初始化游戏
    init: function() {
        console.log('初始化2D射击游戏...');
        
        // 获取Canvas元素
        this.canvas = document.getElementById('game-canvas');
        this.canvas.width = this.width;
        this.canvas.height = this.height;
        this.ctx = this.canvas.getContext('2d');
        
        // 初始化玩家
        this.player = {
            x: this.width / 2,
            y: this.height / 2,
            width: 30,
            height: 30,
            speed: 5,
            health: 100,
            canShoot: true,
            shootCooldown: 200,
            lastShot: 0,
            specialAttack: { active: false, cooldown: 20000, lastUsed: 0 }, // 大招冷却时间改为20秒
            rotation: 0 // 玩家面向角度
        };
        
        // 初始化场景元素
        this.initSceneElements();
        
        // 设置事件监听
        this.setupEventListeners();
        
        // 开始游戏循环
        requestAnimationFrame(this.gameLoop.bind(this));
    },
    
    // 初始化场景元素
    initSceneElements: function() {
        this.sceneElements = [];
        const scene = this.scenes[this.currentScene];
        
        if (scene.stars) {
            for (let i = 0; i < scene.stars; i++) {
                this.sceneElements.push({
                    type: 'star',
                    x: Math.random() * this.width,
                    y: Math.random() * this.height,
                    size: Math.random() * 2,
                    brightness: Math.random() * 0.8 + 0.2
                });
            }
        }
        
        if (scene.trees) {
            for (let i = 0; i < scene.trees; i++) {
                this.sceneElements.push({
                    type: 'tree',
                    x: Math.random() * this.width,
                    y: Math.random() * this.height,
                    height: 30 + Math.random() * 50,
                    width: 10 + Math.random() * 15
                });
            }
        }
        
        if (scene.buildings) {
            for (let i = 0; i < scene.buildings; i++) {
                this.sceneElements.push({
                    type: 'building',
                    x: Math.random() * this.width,
                    y: Math.random() * this.height,
                    height: 40 + Math.random() * 80,
                    width: 20 + Math.random() * 40
                });
            }
        }
    },
    
    // 设置事件监听
    setupEventListeners: function() {
        // 键盘按下
        document.addEventListener('keydown', (event) => {
            this.keys[event.key.toLowerCase()] = true;
            
            // 暂停/继续游戏
            if (event.key.toLowerCase() === 'p' && this.isGameActive) {
                this.togglePause();
            }
        });
        
        // 键盘释放
        document.addEventListener('keyup', (event) => {
            this.keys[event.key.toLowerCase()] = false;
        });
        
        // 鼠标移动
        document.addEventListener('mousemove', (event) => {
            const rect = this.canvas.getBoundingClientRect();
            this.mouse.x = event.clientX - rect.left;
            this.mouse.y = event.clientY - rect.top;
        });
        
        // 鼠标点击射击
        this.canvas.addEventListener('mousedown', (event) => {
            if (this.isGameActive && !this.isPaused) {
                const currentTime = performance.now();
                if (currentTime - this.player.lastShot > this.player.shootCooldown) {
                    this.shoot(this.mouse.x, this.mouse.y);
                    this.player.lastShot = currentTime;
                }
            }
        });
        
        // 开始游戏按钮
        document.getElementById('start-game').addEventListener('click', () => {
            this.startGame();
        });
        
        // 重新开始按钮
        document.getElementById('restart').addEventListener('click', () => {
            this.restartGame();
        });
        
        // 暂停按钮
        document.getElementById('pause-btn').addEventListener('click', () => {
            this.togglePause();
        });
        
        // 恢复游戏按钮
        document.getElementById('resume-btn').addEventListener('click', () => {
            this.togglePause();
        });
        
        // 从暂停菜单返回主菜单
        document.getElementById('restart-btn').addEventListener('click', () => {
            this.restartGame();
        });
    },
    
    // 开始游戏
    startGame: function() {
        console.log('开始游戏');
        
        // 隐藏主菜单
        document.getElementById('main-menu').classList.add('hidden');
        
        // 显示游戏UI
        document.getElementById('game-ui').classList.remove('hidden');
        document.getElementById('controls').classList.remove('hidden');
        
        // 重置游戏状态
        this.resetGame();
        
        // 开始游戏
        this.isGameActive = true;
        this.isPaused = false;
        this.lastTime = performance.now();
    },
    
    // 重新开始游戏
    restartGame: function() {
        // 隐藏游戏结束界面和暂停界面
        document.getElementById('game-over').classList.add('hidden');
        document.getElementById('pause-menu').classList.add('hidden');
        
        // 显示主菜单
        document.getElementById('main-menu').classList.remove('hidden');
    },
    
    // 切换暂停状态
    togglePause: function() {
        this.isPaused = !this.isPaused;
        
        if (this.isPaused) {
            document.getElementById('pause-menu').classList.remove('hidden');
        } else {
            document.getElementById('pause-menu').classList.add('hidden');
        }
    },
    
    // 重置游戏
    resetGame: function() {
        this.score = 0;
        this.health = 100;
        this.enemiesKilled = 0;
        this.enemies = [];
        this.bullets = [];
        this.explosions = [];
        this.particles = [];
        this.powerUps = [];
        this.enemySpawnTimer = 0;
        this.bossSpawnTimer = 0;
        this.enemySpawnRate = 1000; // 普通敌人每秒生成一个
        this.bossSpawnRate = 5000; // Boss每5秒生成一个
        this.level = 1;
        this.currentScene = 0;
        
        // 初始化场景元素
        this.initSceneElements();
        
        // 重置玩家
        this.player.x = this.width / 2;
        this.player.y = this.height / 2;
        this.player.health = 100;
        this.player.lastShot = 0;
        this.player.specialAttack.lastUsed = 0;
        
        // 更新UI
        document.getElementById('score').textContent = this.score;
        document.getElementById('health').textContent = this.health;
        document.getElementById('enemies-count').textContent = this.enemies.length;
        document.getElementById('level').textContent = this.level;
    },
    
    // 游戏循环
    gameLoop: function(currentTime) {
        // 计算时间差
        const deltaTime = currentTime - this.lastTime;
        this.lastTime = currentTime;
        
        // 更新游戏状态
        if (this.isGameActive && !this.isPaused) {
            this.update(deltaTime, currentTime);
        }
        
        // 渲染游戏
        this.render();
        
        // 继续游戏循环
        requestAnimationFrame(this.gameLoop.bind(this));
    },
    
    // 更新游戏状态
    update: function(deltaTime, currentTime) {
        // 更新玩家
        this.updatePlayer(deltaTime, currentTime);
        
        // 生成普通敌人（每秒一个）
        this.enemySpawnTimer += deltaTime;
        if (this.enemySpawnTimer >= this.enemySpawnRate) {
            this.spawnEnemy(false); // 生成普通敌人
            this.enemySpawnTimer = 0;
        }
        
        // 生成Boss（每5秒一个）
        this.bossSpawnTimer += deltaTime;
        if (this.bossSpawnTimer >= this.bossSpawnRate) {
            this.spawnEnemy(true); // 生成Boss
            this.bossSpawnTimer = 0;
        }
        
        // 每1000分升级
        if (Math.floor(this.score / 1000) + 1 > this.level) {
            this.levelUp();
        }
        
        // 更新敌人
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            const enemy = this.enemies[i];
            enemy.update(deltaTime, this.player);
            
            // 检查敌人是否超出边界
            if (enemy.x < -enemy.width || enemy.x > this.width + enemy.width ||
                enemy.y < -enemy.height || enemy.y > this.height + enemy.height) {
                this.enemies.splice(i, 1);
            }
            
            // 检查敌人与玩家的碰撞
            if (this.checkCollision(this.player, enemy)) {
                this.player.health -= enemy.damage * deltaTime / 1000;
                if (this.player.health <= 0) {
                    this.gameOver();
                }
            }
        }
        
        // 更新子弹
        for (let i = this.bullets.length - 1; i >= 0; i--) {
            const bullet = this.bullets[i];
            bullet.update(deltaTime);
            
            // 检查子弹是否超出边界
            if (bullet.x < 0 || bullet.x > this.width || bullet.y < 0 || bullet.y > this.height) {
                this.bullets.splice(i, 1);
                // 添加子弹消失粒子效果
                this.addBulletParticles(bullet.x, bullet.y, bullet.color);
                continue;
            }
            
            // 检查子弹与敌人的碰撞
            for (let j = this.enemies.length - 1; j >= 0; j--) {
                const enemy = this.enemies[j];
                if (this.checkCollision(bullet, enemy)) {
                    // 移除子弹
                    this.bullets.splice(i, 1);
                    // 添加子弹爆炸粒子
                    this.addBulletParticles(bullet.x, bullet.y, bullet.color);
                    
                    // 敌人受伤 - 子弹伤害固定为1，这样boss需要100次击中
                    enemy.health -= 1;
                    
                    // 添加爆炸效果
                    this.addExplosion(enemy.x, enemy.y, enemy.size);
                    
                    // 检查敌人是否死亡
                    if (enemy.health <= 0) {
                        this.enemies.splice(j, 1);
                        // Boss分数更高
                        this.score += enemy.isBoss ? 1000 : 100;
                        this.enemiesKilled++;
                        
                        // 随机生成道具
                        if (Math.random() < 0.1) {
                            this.spawnPowerUp(enemy.x, enemy.y);
                        };
                    }
                    
                    break;
                }
            }
        }
        
        // 更新爆炸效果
        for (let i = this.explosions.length - 1; i >= 0; i--) {
            const explosion = this.explosions[i];
            explosion.update(deltaTime);
            if (explosion.life <= 0) {
                this.explosions.splice(i, 1);
            }
        }
        
        // 更新粒子效果
        for (let i = this.particles.length - 1; i >= 0; i--) {
            const particle = this.particles[i];
            particle.update(deltaTime);
            if (particle.life <= 0) {
                this.particles.splice(i, 1);
            }
        }
        
        // 更新道具
        for (let i = this.powerUps.length - 1; i >= 0; i--) {
            const powerUp = this.powerUps[i];
            powerUp.update(deltaTime);
            
            // 检查道具是否过期
            if (powerUp.life <= 0) {
                this.powerUps.splice(i, 1);
                continue;
            }
            
            // 检查道具与玩家的碰撞
            if (this.checkCollision(this.player, powerUp)) {
                this.collectPowerUp(powerUp);
                this.powerUps.splice(i, 1);
            }
        }
        
        // 更新背景滚动
        this.updateBackground(deltaTime);
        
        // 更新UI
        document.getElementById('score').textContent = this.score;
        document.getElementById('health').textContent = Math.max(0, Math.floor(this.player.health));
        document.getElementById('enemies-count').textContent = this.enemies.length;
        document.getElementById('level').textContent = this.level;
        
        // 更新大招冷却时间显示
        const specialAttackCooldown = this.player.specialAttack.cooldown - (currentTime - this.player.specialAttack.lastUsed);
        const cooldownDisplay = document.getElementById('special-cooldown');
        if (cooldownDisplay) {
            if (specialAttackCooldown > 0) {
                cooldownDisplay.textContent = `大招冷却: ${Math.ceil(specialAttackCooldown / 1000)}秒`;
                cooldownDisplay.classList.add('cooldown-active');
            } else {
                cooldownDisplay.textContent = '大招就绪!';
                cooldownDisplay.classList.remove('cooldown-active');
            }
        } else {
            // 如果冷却时间元素不存在，创建它
            const uiContainer = document.getElementById('game-ui');
            if (uiContainer) {
                const cooldownElement = document.createElement('div');
                cooldownElement.id = 'special-cooldown';
                cooldownElement.style.position = 'absolute';
                cooldownElement.style.top = '10px';
                cooldownElement.style.right = '20px';
                cooldownElement.style.color = 'white';
                cooldownElement.style.fontSize = '16px';
                cooldownElement.style.fontWeight = 'bold';
                cooldownElement.style.textShadow = '1px 1px 2px black';
                uiContainer.appendChild(cooldownElement);
                cooldownElement.textContent = '大招就绪!';
            }
        }
    },
    
    // 更新背景
    updateBackground: function(deltaTime) {
        // 背景滚动效果
        this.backgroundOffsetX += 0.1 * deltaTime / 16;
        this.backgroundOffsetY += 0.05 * deltaTime / 16;
    },
    
    // 升级
    levelUp: function() {
        this.level = Math.floor(this.score / 1000) + 1;
        
        // 切换场景
        this.currentScene = (this.currentScene + 1) % this.scenes.length;
        this.initSceneElements();
        
        // 显示升级提示
        const levelUpText = document.getElementById('level-up');
        levelUpText.textContent = `升级！当前等级：${this.level}\n场景：${this.scenes[this.currentScene].name}`;
        levelUpText.classList.remove('hidden');
        
        setTimeout(() => {
            levelUpText.classList.add('hidden');
        }, 2000);
    },
    
    // 更新玩家
    updatePlayer: function(deltaTime, currentTime) {
        // 移动玩家
        if (this.keys['w']) this.player.y -= this.player.speed;
        if (this.keys['s']) this.player.y += this.player.speed;
        if (this.keys['a']) this.player.x -= this.player.speed;
        if (this.keys['d']) this.player.x += this.player.speed;
        
        // 限制玩家在边界内
        this.player.x = Math.max(this.player.width / 2, Math.min(this.width - this.player.width / 2, this.player.x));
        this.player.y = Math.max(this.player.height / 2, Math.min(this.height - this.player.height / 2, this.player.y));
        
        // 计算玩家面向角度
        const dx = this.mouse.x - this.player.x;
        const dy = this.mouse.y - this.player.y;
        this.player.rotation = Math.atan2(dy, dx);
        
        // 键盘射击（备用）
        if (this.keys[' '] && currentTime - this.player.lastShot > this.player.shootCooldown) {
            this.shoot(this.mouse.x, this.mouse.y);
            this.player.lastShot = currentTime;
        }
        
        // 大招
        if (this.keys['q'] && currentTime - this.player.specialAttack.lastUsed > this.player.specialAttack.cooldown) {
            this.specialAttack();
            this.player.specialAttack.lastUsed = currentTime;
        }
    },
    
    // 射击（鼠标控制方向）
    shoot: function(targetX, targetY) {
        const dx = targetX - this.player.x;
        const dy = targetY - this.player.y;
        const distance = Math.sqrt(dx * dx + dy * dy);
        const bulletSpeed = 12;
        
        // 创建子弹
        const bullet = {
            x: this.player.x,
            y: this.player.y,
            width: 6,
            height: 6,
            speedX: (dx / distance) * bulletSpeed,
            speedY: (dy / distance) * bulletSpeed,
            damage: 1, // 子弹伤害固定为1
            color: '#00ffff',
            update: function(deltaTime) {
                this.x += this.speedX;
                this.y += this.speedY;
            }
        };
        
        this.bullets.push(bullet);
        
        // 添加射击粒子效果
        this.addShootParticles(this.player.x, this.player.y, dx, dy);
    },
    
    // 添加射击粒子效果
    addShootParticles: function(x, y, dx, dy) {
        for (let i = 0; i < 5; i++) {
            const angle = Math.atan2(dy, dx) + (Math.random() - 0.5) * Math.PI / 3;
            const speed = 3 + Math.random() * 2;
            this.particles.push({
                x: x,
                y: y,
                size: 2 + Math.random() * 2,
                speedX: Math.cos(angle) * speed,
                speedY: Math.sin(angle) * speed,
                life: 100 + Math.random() * 100,
                color: '#00ffff',
                update: function(deltaTime) {
                    this.x += this.speedX;
                    this.y += this.speedY;
                    this.life -= deltaTime;
                }
            });
        }
    },
    
    // 添加子弹粒子效果
    addBulletParticles: function(x, y, color) {
        for (let i = 0; i < 8; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = 1 + Math.random() * 3;
            this.particles.push({
                x: x,
                y: y,
                size: 1 + Math.random() * 3,
                speedX: Math.cos(angle) * speed,
                speedY: Math.sin(angle) * speed,
                life: 150 + Math.random() * 150,
                color: color,
                update: function(deltaTime) {
                    this.x += this.speedX;
                    this.y += this.speedY;
                    this.life -= deltaTime;
                }
            });
        }
    },
    
    // 大招
    specialAttack: function() {
        // 创建大范围爆炸效果
        this.addExplosion(this.player.x, this.player.y, 3, true);
        
        // 清除所有敌人
        for (let i = this.enemies.length - 1; i >= 0; i--) {
            const enemy = this.enemies[i];
            // 计算敌人与玩家的距离
            const dx = enemy.x - this.player.x;
            const dy = enemy.y - this.player.y;
            const distance = Math.sqrt(dx * dx + dy * dy);
            
            // 范围内的敌人受到伤害
            if (distance < 150) {
                this.addExplosion(enemy.x, enemy.y, enemy.size);
                this.enemies.splice(i, 1);
                this.score += 50;
                this.enemiesKilled++;
            }
        }
    },
    
    // 生成敌人
    spawnEnemy: function(isBoss) {
        // 随机选择敌人生成位置（屏幕边缘）
        const side = Math.floor(Math.random() * 4);
        let x, y;
        
        switch(side) {
            case 0: // 顶部
                x = Math.random() * this.width;
                y = -50;
                break;
            case 1: // 右侧
                x = this.width + 50;
                y = Math.random() * this.height;
                break;
            case 2: // 底部
                x = Math.random() * this.width;
                y = this.height + 50;
                break;
            case 3: // 左侧
                x = -50;
                y = Math.random() * this.height;
                break;
        }
        
        let enemy;
        
        if (isBoss) {
            // Boss敌人
            enemy = {
                x: x,
                y: y,
                width: 80,
                height: 80,
                size: 3,
                health: 20, // boss需要20次子弹
                maxHealth: 20, // 记录最大血量用于显示
                damage: 50,
                speed: 0.8 + Math.random() * 0.5,
                color: '#880088',
                isBoss: true,
                update: function(deltaTime, player) {
                    // Boss追踪逻辑
                    const dx = player.x - this.x;
                    const dy = player.y - this.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    if (distance > 0) {
                        this.x += (dx / distance) * this.speed;
                        this.y += (dy / distance) * this.speed;
                    }
                }
            };
        } else {
            // 普通敌人
            enemy = {
                x: x,
                y: y,
                width: 25,
                height: 25,
                size: 1,
                health: 1, // 普通敌人一次打死
                damage: 20,
                speed: 2 + Math.random() * 1.5,
                color: '#ff4444',
                update: function(deltaTime, player) {
                    // 简单的追踪逻辑
                    const dx = player.x - this.x;
                    const dy = player.y - this.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    if (distance > 0) {
                        this.x += (dx / distance) * this.speed;
                        this.y += (dy / distance) * this.speed;
                    }
                }
            };
        }
        
        this.enemies.push(enemy);
    },
    
    // 生成道具
    spawnPowerUp: function(x, y) {
        const powerUpType = Math.floor(Math.random() * 4);
        let powerUp;
        
        switch(powerUpType) {
            case 0: // 生命值
                powerUp = {
                    x: x,
                    y: y,
                    width: 20,
                    height: 20,
                    type: 'health',
                    color: '#00ff00',
                    life: 5000,
                    update: function(deltaTime) {
                        this.life -= deltaTime;
                    }
                };
                break;
                
            case 1: // 伤害增强
                powerUp = {
                    x: x,
                    y: y,
                    width: 20,
                    height: 20,
                    type: 'damage',
                    color: '#ff0000',
                    life: 5000,
                    update: function(deltaTime) {
                        this.life -= deltaTime;
                    }
                };
                break;
                
            case 2: // 射速提升
                powerUp = {
                    x: x,
                    y: y,
                    width: 20,
                    height: 20,
                    type: 'speed',
                    color: '#00ffff',
                    life: 5000,
                    update: function(deltaTime) {
                        this.life -= deltaTime;
                    }
                };
                break;
                
            case 3: // 护盾
                powerUp = {
                    x: x,
                    y: y,
                    width: 20,
                    height: 20,
                    type: 'shield',
                    color: '#0000ff',
                    life: 5000,
                    update: function(deltaTime) {
                        this.life -= deltaTime;
                    }
                };
                break;
        }
        
        this.powerUps.push(powerUp);
    },
    
    // 收集道具
    collectPowerUp: function(powerUp) {
        switch(powerUp.type) {
            case 'health':
                this.player.health = Math.min(100, this.player.health + 30);
                break;
                
            case 'damage':
                // 伤害提升效果
                this.player.damageBoost = true;
                setTimeout(() => {
                    this.player.damageBoost = false;
                }, 10000);
                break;
                
            case 'speed':
                // 射速提升效果
                const originalCooldown = this.player.shootCooldown;
                this.player.shootCooldown = 100;
                setTimeout(() => {
                    this.player.shootCooldown = originalCooldown;
                }, 8000);
                break;
                
            case 'shield':
                // 护盾效果
                this.player.shield = true;
                this.player.shieldHealth = 50;
                setTimeout(() => {
                    this.player.shield = false;
                }, 15000);
                break;
        }
        
        // 添加收集特效
        this.addCollectParticles(powerUp.x, powerUp.y, powerUp.color);
    },
    
    // 添加收集粒子效果
    addCollectParticles: function(x, y, color) {
        for (let i = 0; i < 12; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = 2 + Math.random() * 4;
            this.particles.push({
                x: x,
                y: y,
                size: 2 + Math.random() * 3,
                speedX: Math.cos(angle) * speed,
                speedY: Math.sin(angle) * speed,
                life: 200 + Math.random() * 200,
                color: color,
                update: function(deltaTime) {
                    this.x += this.speedX;
                    this.y += this.speedY;
                    this.life -= deltaTime;
                }
            });
        }
    },
    
    // 添加爆炸效果
    addExplosion: function(x, y, size = 1, isSpecial = false) {
        const explosion = {
            x: x,
            y: y,
            radius: 5 * size,
            maxRadius: (isSpecial ? 150 : 50) * size,
            life: 500 * size,
            maxLife: 500 * size,
            color: isSpecial ? '#ff6600' : '#ffaa00',
            update: function(deltaTime) {
                this.life -= deltaTime;
                this.radius += (this.maxRadius / this.maxLife) * deltaTime;
            }
        };
        
        this.explosions.push(explosion);
        
        // 添加爆炸粒子
        const particleCount = isSpecial ? 50 : 20 * size;
        for (let i = 0; i < particleCount; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = 2 + Math.random() * 5 * size;
            this.particles.push({
                x: x,
                y: y,
                size: 2 + Math.random() * 3,
                speedX: Math.cos(angle) * speed,
                speedY: Math.sin(angle) * speed,
                life: 300 + Math.random() * 300,
                color: isSpecial ? '#ff6600' : '#ffaa00',
                update: function(deltaTime) {
                    this.x += this.speedX * 0.95; // 衰减
                    this.y += this.speedY * 0.95;
                    this.life -= deltaTime;
                }
            });
        }
    },
    
    // 检查碰撞
    checkCollision: function(obj1, obj2) {
        return obj1.x < obj2.x + obj2.width &&
               obj1.x + obj1.width > obj2.x &&
               obj1.y < obj2.y + obj2.height &&
               obj1.y + obj1.height > obj2.y;
    },
    
    // 游戏结束
    gameOver: function() {
        this.isGameActive = false;
        
        // 显示游戏结束界面
        document.getElementById('game-ui').classList.add('hidden');
        document.getElementById('controls').classList.add('hidden');
        document.getElementById('game-over').classList.remove('hidden');
        
        // 更新游戏结束UI
        document.getElementById('final-score').textContent = this.score;
        document.getElementById('enemies-killed').textContent = this.enemiesKilled;
        document.getElementById('final-level').textContent = this.level;
        
        // 获取API评价
        this.getGameEvaluation();
    },
    
    // 获取游戏评价
    getGameEvaluation: function() {
        // 调用API获取游戏评价
        const gameData = {
            score: this.score,
            enemiesKilled: this.enemiesKilled,
            level: this.level
        };
        
        // 调用API
        if (window.API) {
            window.API.evaluateGame(gameData)
                .then(feedback => {
                    document.getElementById('api-feedback').textContent = feedback;
                })
                .catch(error => {
                    document.getElementById('api-feedback').textContent = '获取评价失败: ' + error.message;
                });
        } else {
            // 模拟评价
            setTimeout(() => {
                const feedback = document.getElementById('api-feedback');
                feedback.textContent = `游戏评分: ${Math.min(100, Math.floor(this.score / 50))}\n`;
                feedback.textContent += `你消灭了${this.enemiesKilled}个敌人！\n`;
                feedback.textContent += `达到了等级${this.level}！\n`;
                feedback.textContent += `继续努力，下次做得更好！`;
            }, 1000);
        }
    },
    
    // 渲染游戏
    render: function() {
        const scene = this.scenes[this.currentScene];
        
        // 绘制渐变背景
        const gradient = this.ctx.createLinearGradient(0, 0, 0, this.height);
        gradient.addColorStop(0, scene.bgColor);
        gradient.addColorStop(1, scene.gradient);
        this.ctx.fillStyle = gradient;
        this.ctx.fillRect(0, 0, this.width, this.height);
        
        // 渲染场景元素
        this.renderSceneElements();
        
        // 渲染玩家
        this.renderPlayer();
        
        // 渲染敌人
        this.renderEnemies();
        
        // 渲染子弹
        this.renderBullets();
        
        // 渲染爆炸效果
        this.renderExplosions();
        
        // 渲染粒子
        this.renderParticles();
        
        // 渲染道具
        this.renderPowerUps();
        
        // 渲染暂停覆盖层
        if (this.isPaused) {
            this.ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
            this.ctx.fillRect(0, 0, this.width, this.height);
        }
    },
    
    // 渲染场景元素
    renderSceneElements: function() {
        const scene = this.scenes[this.currentScene];
        
        this.sceneElements.forEach(element => {
            this.ctx.save();
            
            switch(element.type) {
                case 'star':
                    this.ctx.fillStyle = `rgba(255, 255, 255, ${element.brightness})`;
                    this.ctx.beginPath();
                    this.ctx.arc(
                        (element.x + this.backgroundOffsetX) % this.width,
                        (element.y + this.backgroundOffsetY) % this.height,
                        element.size,
                        0,
                        Math.PI * 2
                    );
                    this.ctx.fill();
                    break;
                    
                case 'tree':
                    // 树干
                    this.ctx.fillStyle = '#654321';
                    this.ctx.fillRect(
                        (element.x + this.backgroundOffsetX * 0.3) % this.width - element.width / 4,
                        (element.y + this.backgroundOffsetY * 0.3) % this.height - element.height / 2,
                        element.width / 2,
                        element.height / 2
                    );
                    // 树叶
                    this.ctx.fillStyle = '#006600';
                    this.ctx.beginPath();
                    this.ctx.arc(
                        (element.x + this.backgroundOffsetX * 0.3) % this.width,
                        (element.y + this.backgroundOffsetY * 0.3) % this.height - element.height / 2,
                        element.width,
                        0,
                        Math.PI
                    );
                    this.ctx.fill();
                    break;
                    
                case 'building':
                    this.ctx.fillStyle = '#333333';
                    this.ctx.fillRect(
                        (element.x + this.backgroundOffsetX * 0.1) % this.width - element.width / 2,
                        (element.y + this.backgroundOffsetY * 0.1) % this.height - element.height / 2,
                        element.width,
                        element.height
                    );
                    // 窗户
                    this.ctx.fillStyle = '#ffff00';
                    const windowWidth = 4;
                    const windowHeight = 6;
                    const windowSpacingX = 8;
                    const windowSpacingY = 10;
                    
                    for (let wx = 0; wx < Math.floor((element.width - windowSpacingX) / (windowWidth + windowSpacingX)); wx++) {
                        for (let wy = 0; wy < Math.floor((element.height - windowSpacingY) / (windowHeight + windowSpacingY)); wy++) {
                            if (Math.random() > 0.3) { // 有些窗户是暗的
                                this.ctx.fillRect(
                                    (element.x + this.backgroundOffsetX * 0.1) % this.width - element.width / 2 + windowSpacingX + wx * (windowWidth + windowSpacingX),
                                    (element.y + this.backgroundOffsetY * 0.1) % this.height - element.height / 2 + windowSpacingY + wy * (windowHeight + windowSpacingY),
                                    windowWidth,
                                    windowHeight
                                );
                            }
                        }
                    }
                    break;
            }
            
            this.ctx.restore();
        });
    },
    
    // 渲染玩家
    renderPlayer: function() {
        this.ctx.save();
        this.ctx.translate(this.player.x, this.player.y);
        this.ctx.rotate(this.player.rotation);
        
        // 绘制玩家主体
        this.ctx.fillStyle = '#00ff00';
        this.ctx.beginPath();
        this.ctx.moveTo(0, -this.player.height / 2);
        this.ctx.lineTo(-this.player.width / 2, this.player.height / 2);
        this.ctx.lineTo(this.player.width / 2, this.player.height / 2);
        this.ctx.closePath();
        this.ctx.fill();
        
        // 绘制玩家边框
        this.ctx.strokeStyle = '#00cc00';
        this.ctx.lineWidth = 2;
        this.ctx.stroke();
        
        // 如果有护盾，绘制护盾
        if (this.player.shield) {
            const shieldOpacity = Math.min(1, this.player.shieldHealth / 50);
            this.ctx.strokeStyle = `rgba(0, 0, 255, ${shieldOpacity})`;
            this.ctx.lineWidth = 3;
            this.ctx.beginPath();
            this.ctx.arc(0, 0, this.player.width * 1.5, 0, Math.PI * 2);
            this.ctx.stroke();
        }
        
        this.ctx.restore();
    },
    
    // 渲染敌人
    renderEnemies: function() {
        this.enemies.forEach(enemy => {
            this.ctx.save();
            this.ctx.translate(enemy.x, enemy.y);
            
            // 绘制敌人主体
            this.ctx.fillStyle = enemy.color;
            
            // 根据敌人类型绘制不同形状
            if (enemy.isBoss) { // Boss敌人
                // Boss外观
                this.ctx.fillRect(-enemy.width / 2, -enemy.height / 2, enemy.width, enemy.height);
                // Boss细节
                this.ctx.fillStyle = '#aa00aa';
                this.ctx.fillRect(-enemy.width / 3, -enemy.height / 2, enemy.width / 3, enemy.height / 4);
                this.ctx.fillRect(0, -enemy.height / 2, enemy.width / 3, enemy.height / 4);
                // Boss边框
                this.ctx.strokeStyle = '#ffffff';
                this.ctx.lineWidth = 3;
                this.ctx.strokeRect(-enemy.width / 2, -enemy.height / 2, enemy.width, enemy.height);
            } else if (enemy.width === 25) { // 普通敌人
                this.ctx.fillRect(-enemy.width / 2, -enemy.height / 2, enemy.width, enemy.height);
                // 绘制敌人边框
                this.ctx.strokeStyle = '#ffffff';
                this.ctx.lineWidth = 1;
                this.ctx.strokeRect(-enemy.width / 2, -enemy.height / 2, enemy.width, enemy.height);

            }
            
            // 渲染敌人血条
            if (enemy.isBoss) {
                // Boss大血条
                const barWidth = 120;
                const barHeight = 8;
                // 血条背景
                this.ctx.fillStyle = '#333333';
                this.ctx.fillRect(-barWidth / 2, -enemy.height / 2 - 20, barWidth, barHeight);
                // 血条边框
                this.ctx.strokeStyle = '#666666';
                this.ctx.lineWidth = 2;
                this.ctx.strokeRect(-barWidth / 2, -enemy.height / 2 - 20, barWidth, barHeight);
                // 血条填充
                this.ctx.fillStyle = '#ff0000';
                this.ctx.fillRect(-barWidth / 2, -enemy.height / 2 - 20, (enemy.health / enemy.maxHealth) * barWidth, barHeight);
                // Boss文字标签
                this.ctx.fillStyle = '#ffffff';
                this.ctx.font = '12px Arial';
                this.ctx.textAlign = 'center';
                this.ctx.fillText('BOSS', 0, -enemy.height / 2 - 35);
                // 显示剩余血量
                this.ctx.fillText(`${enemy.health}/20`, 0, -enemy.height / 2 + enemy.height / 2 + 30);
            } else {
                // 普通敌人血条（小）
                this.ctx.fillStyle = '#333333';
                this.ctx.fillRect(-25, -40, 50, 3);
                this.ctx.fillStyle = '#ff0000';
                this.ctx.fillRect(-25, -40, 50, 3); // 普通敌人满血显示
            }
            
            this.ctx.restore();
        });
    },
    
    // 渲染子弹
    renderBullets: function() {
        this.bullets.forEach(bullet => {
            this.ctx.save();
            this.ctx.translate(bullet.x, bullet.y);
            
            // 计算子弹角度
            const angle = Math.atan2(bullet.speedY, bullet.speedX);
            this.ctx.rotate(angle);
            
            // 绘制子弹
            this.ctx.fillStyle = bullet.color;
            this.ctx.fillRect(-bullet.width / 2, -bullet.height / 2, bullet.width, bullet.height);
            
            this.ctx.restore();
        });
    },
    
    // 渲染爆炸效果
    renderExplosions: function() {
        this.explosions.forEach(explosion => {
            const alpha = explosion.life / explosion.maxLife;
            this.ctx.fillStyle = `rgba(${explosion.color === '#ff6600' ? '255, 102, 0' : '255, 170, 0'}, ${alpha})`;
            this.ctx.beginPath();
            this.ctx.arc(explosion.x, explosion.y, explosion.radius, 0, Math.PI * 2);
            this.ctx.fill();
        });
    },
    
    // 渲染粒子
    renderParticles: function() {
        this.particles.forEach(particle => {
            const alpha = particle.life / 300;
            this.ctx.fillStyle = `rgba(${this.hexToRgb(particle.color)}, ${alpha})`;
            this.ctx.beginPath();
            this.ctx.arc(particle.x, particle.y, particle.size, 0, Math.PI * 2);
            this.ctx.fill();
        });
    },
    
    // 渲染道具
    renderPowerUps: function() {
        this.powerUps.forEach(powerUp => {
            // 计算道具闪烁效果
            const pulse = Math.sin(Date.now() * 0.005) * 0.5 + 0.5;
            const alpha = 0.7 + pulse * 0.3;
            
            this.ctx.save();
            this.ctx.translate(powerUp.x, powerUp.y);
            
            // 绘制道具基础形状
            this.ctx.fillStyle = `rgba(${this.hexToRgb(powerUp.color)}, ${alpha})`;
            this.ctx.beginPath();
            
            // 根据道具类型绘制不同形状
            switch(powerUp.type) {
                case 'health':
                    // 心形
                    this.ctx.moveTo(0, -powerUp.height / 2);
                    this.ctx.bezierCurveTo(-powerUp.width / 2, -powerUp.height, -powerUp.width, 0, 0, powerUp.height / 2);
                    this.ctx.bezierCurveTo(powerUp.width, 0, powerUp.width / 2, -powerUp.height, 0, -powerUp.height / 2);
                    break;
                    
                case 'damage':
                    // 星形
                    for (let i = 0; i < 5; i++) {
                        const angle = i * Math.PI * 0.4 - Math.PI / 2;
                        const x = Math.cos(angle) * powerUp.width / 2;
                        const y = Math.sin(angle) * powerUp.height / 2;
                        if (i === 0) {
                            this.ctx.moveTo(x, y);
                        } else {
                            this.ctx.lineTo(x, y);
                        }
                        
                        const innerAngle = (i + 0.5) * Math.PI * 0.4 - Math.PI / 2;
                        const innerX = Math.cos(innerAngle) * powerUp.width / 4;
                        const innerY = Math.sin(innerAngle) * powerUp.height / 4;
                        this.ctx.lineTo(innerX, innerY);
                    }
                    break;
                    
                case 'speed':
                    // 闪电形状
                    this.ctx.moveTo(-powerUp.width / 3, -powerUp.height / 3);
                    this.ctx.lineTo(0, -powerUp.height / 2);
                    this.ctx.lineTo(powerUp.width / 3, -powerUp.height / 3);
                    this.ctx.lineTo(0, 0);
                    this.ctx.lineTo(powerUp.width / 3, powerUp.height / 3);
                    this.ctx.lineTo(0, powerUp.height / 2);
                    this.ctx.lineTo(-powerUp.width / 3, powerUp.height / 3);
                    this.ctx.closePath();
                    break;
                    
                case 'shield':
                    // 六边形
                    for (let i = 0; i < 6; i++) {
                        const angle = i * Math.PI * 0.3333 - Math.PI / 6;
                        const x = Math.cos(angle) * powerUp.width / 2;
                        const y = Math.sin(angle) * powerUp.height / 2;
                        if (i === 0) {
                            this.ctx.moveTo(x, y);
                        } else {
                            this.ctx.lineTo(x, y);
                        }
                    }
                    break;
            }
            
            this.ctx.closePath();
            this.ctx.fill();
            
            // 绘制边框
            this.ctx.strokeStyle = `rgba(255, 255, 255, ${alpha})`;
            this.ctx.lineWidth = 2;
            this.ctx.stroke();
            
            this.ctx.restore();
        });
    },
    
    // 辅助函数：将十六进制颜色转换为RGB字符串
    hexToRgb: function(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? `${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}` : '255, 255, 255';
    }
};

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', function() {
    GAME.init();
});